package com.wocai.jrt.orgadmin.device.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.action.PageBean;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.device.bean.PosPadReqBean;
import com.wocai.jrt.orgadmin.device.bean.PosPadResBean;
import com.wocai.jrt.orgadmin.device.model.PosPad;
import com.wocai.jrt.orgadmin.device.service.spi.PosPadService;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.investor.bean.EmpBreifBean;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 设备控制器
 * 
 * @author yinlei
 * @date 2015-8-17 17:03:44
 */
@Controller
@RequestMapping("/device")
public class PosPadAction extends GenericAction<PosPad> {
	private static final Logger LOGGER = LoggerFactory.getLogger(PosPadAction.class);

	@Inject
	private PosPadService posPadServiceImpl;
	@Inject
	private EmployeeService employeeServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获得pos和pad关联表List，Json格式。
	 * 
	 * @param model
	 *            参数
	 * @return pos和pad关联表List
	 */
	@RequestMapping("/list")
	public String list(PosPad model, PageBean<PosPad> pageBean, Map<String, Object> maps) {
		try {
			LOGGER.info("device list param: [{}]",JSON.toJSONString(model));
			List<PosPad> list = posPadServiceImpl.pagedList(model);
			maps.put("deviceList", list);
		} catch (Exception e) {
			LOGGER.error("init device list error, msg=[{}].", e.getMessage());
		}
		return "device/list";
	}

	/**
	 * 查询设备，以及初始化列表页面
	 * 
	 * @param pp参数
	 * @return 查询结果json
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody PosPadReqBean pp) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			LOGGER.info("query device param: [{}]",JSON.toJSONString(pp));
			List<PosPadResBean> list = posPadServiceImpl.getPosPadList(pp);

			// 统计的时候，不需要分页
			pp.setPage(null);
			long totalRecord = posPadServiceImpl.getPosPadCount(pp);

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("device query success.");
			}
			// jQuery datatable
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("device query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 申请报修。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 设备详情页
	 */
	@ResponseBody
	@RequestMapping("/repair")
	public JsonBean repair(@RequestBody PosPad model) {
		JsonBean json = new JsonBean();
		if (StringUtils.isBlank(model.getId())) {
			LOGGER.info("参数为空.");
			json.setCode(0);
			json.setMessage("参数为空.");
			return json;
		}
		try {
			// 2 - 报修
			model.setState(2);
			int result = posPadServiceImpl.updateById(model);
			if (1 == result) {
				LOGGER.info("报修成功.");
				json.setCode(1);
				json.setMessage(SUCCESS);
			} else {
				LOGGER.info("报修不成功.");
				json.setCode(0);
				json.setMessage("报修不成功.");
			}
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			json.setCode(0);
			json.setMessage("报修不成功.");
		}
		return json;
	}

	/**
	 * 设备归还。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 设备归还结果
	 */
	@ResponseBody
	@RequestMapping("/pullback")
	public JsonBean pullback(@RequestBody PosPad model) {
		JsonBean json = new JsonBean();
		if (StringUtils.isBlank(model.getId())) {
			LOGGER.info("参数为空.");
			json.setCode(0);
			json.setMessage(ERROR);
			return json;
		}
		try {
			int result = posPadServiceImpl.pullbackDevice(model.getId());
			if (1 == result) {
				LOGGER.info("归还成功.");
				json.setCode(1);
				json.setMessage(SUCCESS);
			} else {
				LOGGER.info("归还失败.");
				json.setCode(0);
				json.setMessage(ERROR);
			}
		} catch (Exception e) {
			LOGGER.error("pullback device error, errorMsg=[{}].", e.getMessage());
			json.setCode(0);
			json.setMessage(ERROR);
		}
		return json;
	}

	/**
	 * 分配的设备详情加载。
	 * 
	 * @param model
	 *            参数
	 * @return pos和pad关联表List
	 */
	@ResponseBody
	@RequestMapping("/distribution")
	public PosPadResBean distribution(@RequestBody PosPadReqBean model, PageBean<PosPad> pageBean) {
		LOGGER.info("分配设备参数: [{}]",JSON.toJSONString(model));
		PosPadResBean ps = new PosPadResBean();
		try {
			ps = posPadServiceImpl.getPosPadList(model).get(0);
		} catch (Exception e) {
			LOGGER.info("参数错误");
		}
		return ps;
	}

	/**
	 * 执行设备分配。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 设备归还结果
	 */
	@ResponseBody
	@RequestMapping("/doDistributionOther")
	public JsonBean doDistributionOther(@RequestBody PosPadReqBean model) {
		JsonBean json = new JsonBean();
		if (StringUtils.isAnyBlank(model.getId(), model.getEmployeeId())) {
			LOGGER.info("参数为空.");
			json.setCode(0);
			json.setMessage("参数为空.");
			return json;
		}
		try {
			Employee employee = employeeServiceImpl.get(model.getEmployeeId());
			if (null == employee) {
				LOGGER.info("员工不存在");
				json.setCode(0);
				json.setMessage("员工不存在");
				return json;
			}
			model.setEmployeeId(employee.getEmployeeId());
			model.setAllocatedTime(new Date());
			int result = posPadServiceImpl.distributeDevice(model);
			if (1 == result) {
				LOGGER.info("分配成功.");
				json.setCode(1);
				json.setMessage(SUCCESS);
			} else if (2 == result) {
				LOGGER.info("该员工已领取设备.");
				json.setCode(0);
				json.setMessage("该员工已领取设备.");
			} else {
				LOGGER.info("分配失败.");
				json.setCode(0);
				json.setMessage("分配失败.");
			}
		} catch (Exception e) {
			LOGGER.error("pullback device error, errorMsg=[{}].", e.getMessage());
			json.setCode(0);
			json.setMessage("分配失败.");
		}
		return json;
	}
	
	/**
	 * 执行设备分配。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 设备归还结果
	 */
	@ResponseBody
	@RequestMapping("/doDistribution")
	public JsonBean doDistribution(@RequestBody PosPadReqBean model) {
		JsonBean json = new JsonBean();
		if (StringUtils.isAnyBlank(model.getId(), model.getEmployeeNo())) {
			LOGGER.info("参数为空.");
			json.setCode(0);
			json.setMessage("参数为空.");
			return json;
		}
		try {
			Employee employee = new Employee();
			employee.setEmployeeNo(model.getEmployeeNo());
			employee.setOrgId(UserUtils.getOrgId());
			employee = employeeServiceImpl.unique(employee);
			if (null == employee) {
				LOGGER.info("员工不存在");
				json.setCode(0);
				json.setMessage("员工不存在");
				return json;
			}
			model.setEmployeeId(employee.getEmployeeId());
			model.setAllocatedTime(new Date());
			int result = posPadServiceImpl.distributeDevice(model);
			if (1 == result) {
				LOGGER.info("分配成功.");
				json.setCode(1);
				json.setMessage(SUCCESS);
			} else if (2 == result) {
				LOGGER.info("该员工已领取设备.");
				json.setCode(0);
				json.setMessage("该员工已领取设备.");
			} else {
				LOGGER.info("分配失败.");
				json.setCode(0);
				json.setMessage("分配失败.");
			}
		} catch (Exception e) {
			LOGGER.error("pullback device error, errorMsg=[{}].", e.getMessage());
			json.setCode(0);
			json.setMessage("分配失败.");
		}
		return json;
	}
	
	/**
	 * 查询机构下的理财师。
	 * 
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@ResponseBody
	@RequestMapping("/employee/{employeeKey}")
	public List<EmpBreifBean> employee(@PathVariable("employeeKey") String employeeKey) {
		JsonBean bean = new JsonBean();
		try {
			// 查询该机构下所有理财师列表
			List<EmpBreifBean> eBean = posPadServiceImpl.getOrgEmployeeList(
					UserUtils.getOrgId(), employeeKey);
			return eBean;
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage("获取机构理财师列表失败: [{}]" + e.getMessage());
			LOGGER.error("get Investor list error, errorMsg=[{}].", e.getMessage());
		}
		return null;
	}

	/**
	 * 根据pad编号，查询对应的机构的pos机编号
	 * 
	 * @param model
	 *            参数
	 * @return 设备信息
	 */
	@ResponseBody
	@RequestMapping("/queryPosPad")
	public PosPad queryPosPad(PosPad model) {
		if (StringUtils.isBlank(model.getPadId())) {
			return null;
		}
		try {
			model.setOrgId(UserUtils.getOrgId());
			model = posPadServiceImpl.queryPosPadInfo(model);
		} catch (Exception e) {
			LOGGER.error("queryPosPad error, msg=[{}].", e.getMessage());
		}
		return model;
	}
	
	/**
	 * 根据pad编号，查询对应的机构的pos机编号
	 * 
	 * @param model
	 *            参数
	 * @return 设备信息
	 */
	@ResponseBody
	@RequestMapping("/queryPosPadAuto/{key}")
	public List<PosPadResBean> queryPosPadAuto(@PathVariable("key") String key) {
		List<PosPadResBean> posPadList = null;
		try {
			PosPadReqBean reqBean = new PosPadReqBean();
			reqBean.setOrgId(UserUtils.getOrgId());
			reqBean.setpSerialNumber(key);
			reqBean.setAllocated(0);
			posPadList = posPadServiceImpl.queryPosPadAuto(reqBean);
		} catch (Exception e) {
			LOGGER.error("queryPosPad error, msg=[{}].", e.getMessage());
		}
		return posPadList;
	}
}
